import hashlib
from flask import jsonify
from flask import request
from flask_restful import Resource

from OAPro.Blueprint import blueprint
from OAPro import api
from OAPro.models import Account
from flask_jwt import jwt_required

def setPassword(password):
    md5 = hashlib.md5()
    md5.update(password.encode())
    result = md5.hexdigest()
    return result

class BaseViewSet(Resource):
    def __init__(self):
        self.result = {
            'version': "v1.0",
            'code': 200,
            'data': []
        }

class AccountViewSet(BaseViewSet):
    #除了注册用户之外其他操作需要登陆之后操作

    method_decorators = {
        "get": [jwt_required()],
        "put": [jwt_required()],
        "delete": [jwt_required()]
    }
    def get(self):
        return jsonify(self.result)

    def serializer(self,obj):
        return [
                    {"id": i.id,
                     "username": i.username,
                     "password": i.password,
                     "is_activate": i.is_activate}for i in obj
        ]

    def post(self):
        """
        完成用户注册
        """
        data = request.form
        username = data.get("username")
        password = data.get("password")
        is_activate = data.get("is_activate",0)
        if username and password:
            user = Account()
            user.username = username
            user.password = setPassword(password)
            user.is_activate = is_activate
            try:
                user.save()
                self.result["data"].append(self.serializer([user]))
            except Exception as e:
                self.result['code'] = 500
                self.result['data'] = str(e)
        else:
            self.result['code'] = 500
            self.result['data'] = "用户名和密码不可以为空"
        return jsonify(self.result)

    def put(self):
        return jsonify(self.result)

    def delete(self):
        return jsonify(self.result)

api.add_resource(
    AccountViewSet,
    '/account/'
)